const sqlPromise = require("../db/sqlPromise");
const bcrypt = require("bcryptjs");
const jwt = require("jsonwebtoken"); // 生成token
const { secretKey } = require("../../code/config");

let regUser = async (req, res) => {
  let sql = "select * from ev_users where username=?";
  let results = await sqlPromise(sql, [req.body.username]);
  console.log(results);
  if (results.length > 0) return res.send({ status: 1, msg: "用户名已存在" });
  let serectPwd = bcrypt.hashSync(req.body.password, 10);
  let insertSql = "insert into ev_users (username,password) values (?,?)";
  let insertRes = await sqlPromise(insertSql, [req.body.username, serectPwd]);
  console.log(insertRes);
  if (insertRes.affectedRows != 1)
    return res.send({ msg: "添加失败 未知错误" });
  res.send({ msg: "注册成功", status: 200 });
};

let login = async (req, res) => {
  let sql = "select * from ev_users where username=?";
  let results = await sqlPromise(sql, [req.body.username]);
  if (!results.length) return res.send({ status: 1, msg: "用户不存在" });
  console.log(results);
  let queryPwd = results[0].password;
  const compareResult = bcrypt.compareSync(req.body.password, queryPwd);
  if (!compareResult) return res.send({ status: 1, msg: "密码错误" });
  let user = { ...results[0], password: "", user_pic: "" };
  let token = jwt.sign(user, secretKey, { expiresIn: "60s" });
  res.send({
    status: 1,
    msg: "登录成功",
    token: "Bearer " + token,
  });
};

module.exports = {
  regUser,
  login,
};
